import { useEffect, useState } from 'react'
import { Swiper, View } from '@tarojs/components'

import './index.scss'

type TabProps = {
  className?: string
  tabList: TabArray[]
  initialTab?: number
  children: React.ReactNode
  onTabClick?: Function
  onChange?: Function
}

type SwiperProps = {
  detail: {
    current: number
  }
}

const Tab = ({
  className,
  tabList = [],
  initialTab,
  children,
  onTabClick,
  onChange
}: TabProps): JSX.Element => {
  const [current, setCurrent] = useState(0)

  useEffect(() => {
    setCurrent(initialTab || tabList[0].id)
  }, [])

  const handleClickTab = (id: number) => {
    setCurrent(id)
    onTabClick && onTabClick(id)
  }

  const handleChangeSwiper = (e: SwiperProps) => {
    const { current: id } = e.detail
    setCurrent(id)
    onChange && onChange(e)
  }

  const innerStyle = {
    width: `${100 / tabList.length}%`,
    transform: `translateX(${current * 100}%)`
  }

  return (
    <View className={`tab-container ${className}`}>
      <View className='tab-bar'>
        {tabList.map(
          ({ label, id }, index): JSX.Element => (
            <View
              className={`tab-item ${current === id ? 'active' : ''}`}
              key={id || index}
              onClick={() => handleClickTab(id)}
            >
              {label}
            </View>
          )
        )}
        <View className='scroll-bar' style={innerStyle}></View>
      </View>

      {/* tab选项卡中对应的内容 */}
      <Swiper current={current} className='tab-content' onChange={handleChangeSwiper}>
        {children}
      </Swiper>
    </View>
  )
}

export default Tab
